﻿Imports System.Drawing.Imaging
Imports System.IO

Public Class XFormAgregarParticipante
    Private EsNuevo As Boolean
    Private IDP As Integer
    Dim OrdenActual As Integer

    Public Property EsNuevo1() As Boolean
        Get
            Return EsNuevo
        End Get
        Set(value As Boolean)
            EsNuevo = value
        End Set
    End Property

    Public Property IDP1() As Integer
        Get
            Return IDP
        End Get
        Set(value As Integer)
            IDP = value
        End Set
    End Property

    Private Sub XFormAgregarParticipante_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        ParticipantesBindingSource.CancelEdit()
    End Sub


    Private Sub XFormAgregarParticipante_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        CarrerasTableAdapter.Fill(DsEvento.Carreras)
        SexoTableAdapter.Fill(DsEvento.Sexo)

        If EsNuevo Then
            ParticipantesBindingSource.AddNew()
            btnOK.Text = "Agregar participante"
        Else
            btnOK.Text = "Actualizar"
            ParticipantesTableAdapter.FillByIDParticipante(DsEvento.Participantes, IDP)
            OrdenActual = OrdenParticipacionTextEdit.EditValue
        End If
    End Sub

    Private Sub btnOK_Click(sender As System.Object, e As System.EventArgs) Handles btnOK.Click
        If Not ValidarFormulario() Then
            Exit Sub
        End If

        If EsNuevo Then

            If FotografíaPictureBox.Image Is Nothing Then
                Dim SinFoto() As Byte = Nothing
                ParticipantesTableAdapter.Insert(OrdenParticipacionTextEdit.EditValue, NombreTextEdit.EditValue, ApellidoTextEdit.EditValue, FechaNacimientoDateEdit.EditValue, SinFoto, IDSexoLookUpEdit.EditValue, EventoActivo.IDEvento, IDCarreraLookUpEdit.EditValue)
            Else
                Dim arrFilename() As String = Split(Text, "\")
                Array.Reverse(arrFilename)

                Using ms As New MemoryStream()
                    FotografíaPictureBox.Image.Save(ms, FotografíaPictureBox.Image.RawFormat)
                    Dim arrImage() As Byte = ms.GetBuffer
                    ParticipantesTableAdapter.Insert(OrdenParticipacionTextEdit.EditValue, NombreTextEdit.EditValue, ApellidoTextEdit.EditValue, FechaNacimientoDateEdit.EditValue, arrImage, IDSexoLookUpEdit.EditValue, EventoActivo.IDEvento, IDCarreraLookUpEdit.EditValue)
                End Using
            End If

            With XFormParticipantes
                .Cargar()
                .Show()
                .Focus()
            End With
            Close()
        Else
            If FotografíaPictureBox.Image Is Nothing Then
                Dim SinFoto() As Byte = Nothing
                ParticipantesTableAdapter.UpdateParticipante(OrdenParticipacionTextEdit.EditValue, NombreTextEdit.EditValue, ApellidoTextEdit.EditValue, FechaNacimientoDateEdit.EditValue, SinFoto, IDSexoLookUpEdit.EditValue, EventoActivo.IDEvento, IDCarreraLookUpEdit.EditValue, IDP)
            Else
                Dim arrFilename() As String = Split(Text, "\")
                Array.Reverse(arrFilename)

                Using ms As New MemoryStream()
                    FotografíaPictureBox.Image.Save(ms, FotografíaPictureBox.Image.RawFormat)
                    Dim arrImage() As Byte = ms.GetBuffer
                    ParticipantesTableAdapter.UpdateParticipante(OrdenParticipacionTextEdit.EditValue, NombreTextEdit.EditValue, ApellidoTextEdit.EditValue, FechaNacimientoDateEdit.EditValue, arrImage, IDSexoLookUpEdit.EditValue, EventoActivo.IDEvento, IDCarreraLookUpEdit.EditValue, IDP)
                End Using
            End If
         
            With XFormParticipantes
                .Cargar()
                .Show()
                .Focus()
            End With
            Close()
        End If
    End Sub

    Private Function ValidarFormulario() As Boolean
        If NombreTextEdit.EditValue Is DBNull.Value Then
            NombreTextEdit.Focus()
            Return False
        End If

        If ApellidoTextEdit.EditValue Is DBNull.Value Then
            ApellidoTextEdit.Focus()
            Return False
        End If

        If FechaNacimientoDateEdit.EditValue Is DBNull.Value Then
            MsgBox("Selecciona la fecha de nacimiento", MsgBoxStyle.Exclamation, "Datos incompletos")
            Return False
        End If

        If OrdenParticipacionTextEdit.EditValue Is DBNull.Value Then
            OrdenParticipacionTextEdit.Focus()
            Return False
        End If

        If IDSexoLookUpEdit.EditValue Is DBNull.Value Then
            MsgBox("Debes seleccionar el sexo", MsgBoxStyle.Exclamation, "Datos incompletos")
            Return False
        End If

        If IDCarreraLookUpEdit.EditValue Is DBNull.Value Then
            MsgBox("Debes seleccionar la carrera", MsgBoxStyle.Exclamation, "Datos incompletos")
            Return False
        End If

        If EsNuevo Then
            Using DtParticipantes As DataTable = ParticipantesTableAdapter.GetDataByOrdenParticipacion(OrdenParticipacionTextEdit.EditValue, EventoActivo.IDEvento, IDSexoLookUpEdit.EditValue)
                If DtParticipantes.Rows.Count = 1 Then
                    MsgBox(String.Format("Este turno de participación ya fué asignado al participante {0} {1}", DtParticipantes(0)(2), DtParticipantes(0)(3)), MsgBoxStyle.Exclamation, "Orden")
                    OrdenParticipacionTextEdit.Focus()
                    Return False
                End If
            End Using
        Else
            Using DtParticipantes As DataTable = ParticipantesTableAdapter.GetDataByOrdenParticipacion2(OrdenParticipacionTextEdit.EditValue, OrdenActual, EventoActivo.IDEvento, IDSexoLookUpEdit.EditValue)
                If DtParticipantes.Rows.Count = 1 Then
                    MsgBox(String.Format("Este turno de participación ya fué asignado al participante {0} {1}", DtParticipantes(0)(2), DtParticipantes(0)(3)), MsgBoxStyle.Exclamation, "Orden")
                    OrdenParticipacionTextEdit.Focus()
                    Return False
                End If
            End Using
        End If

        Return True
    End Function

    Private Sub FotografíaPictureBox_DoubleClick_1(sender As System.Object, e As System.EventArgs) Handles FotografíaPictureBox.DoubleClick
        OpenF.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyPictures
        OpenF.Filter = "Imágenes (*.png, *.jpg) | *.png;*.jpg"
        OpenF.FileName = "Selecciona una imagen"
        Try
            If OpenF.ShowDialog = Windows.Forms.DialogResult.OK Then
                FotografíaPictureBox.Image = Image.FromFile(OpenF.FileName)
            End If
        Catch ex As Exception
            MsgBox("Ocurrió un error inesperado", MsgBoxStyle.Critical, "Error")
        End Try
    End Sub

    Private Sub FotografíaPictureBox_ParseEditValue(sender As System.Object, e As DevExpress.XtraEditors.Controls.ConvertEditValueEventArgs) Handles FotografíaPictureBox.ParseEditValue
        If TypeOf e.Value Is Bitmap Then
            e.Value = imageToByteArray(e.Value)
            e.Handled = True
        End If
    End Sub

    Public Function imageToByteArray(ByVal imageIn As Image) As Byte()
        Dim MS As New MemoryStream
        imageIn.Save(MS, Imaging.ImageFormat.Png)
        Return MS.ToArray
    End Function
End Class